package com.park.oss.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.park.oss.model.Payment;
import com.park.oss.model.PlaceRent;
import com.park.oss.model.PlaceRentRule;
import com.park.oss.model.SysUser;
import com.park.oss.model.UserBalance;
import com.park.oss.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	SQLManager sqlManager ;
	@Override
	public List<SysUser> query(Integer parkId,Integer hasPlace) {
		Map paras = new HashMap();
		paras.put("parkId", parkId);
		paras.put("hasPlace", hasPlace);
		return sqlManager.select("user.all", SysUser.class, paras,1,10);
	}
	@Override
	public List<Payment> queryPayment(Integer userId) {
		Map paras = new HashMap();
		paras.put("userId", userId);
		return sqlManager.select("user.payment", Payment.class, paras,1,10);
	}
	@Override
	public PlaceRentRule getRentRule(Integer userId) {
		PlaceRentRule rule = new PlaceRentRule();
		rule.setUserId(userId);
		List<PlaceRentRule> list = sqlManager.template(rule);
		if(list.size()==0) return  null;
		else return list.get(0);
		
	}
	@Override
	public List<PlaceRent> getRent(Integer userId) {
		PlaceRent rule = new PlaceRent();
		rule.setOwnerId(userId);
		List<PlaceRent> list = sqlManager.select("placeRent.select", PlaceRent.class, rule,1,50);
		return list;
	}
	@Override
	public SysUser getUser(Integer userId) {
		return sqlManager.unique(SysUser.class, userId);
	}
	@Override
	public SysUser getUser(String mobile, String password) {
		SysUser query = new SysUser();
		query.setMobile(mobile);
		
		List<SysUser> users = sqlManager.template(query);
		if(users.size()==0){
			return null;
		}else{
			SysUser user =  users.get(0);
			if(user.getPassword().equals(password)){
				return user;
			}else{
				throw new RuntimeException("用户名密码错！");
			}
		}
	}
	@Override
	public SysUser addUser(String mobile, String pwd) {
		SysUser user = new SysUser();
		user.setMobile(mobile);
		user.setPassword(pwd);
//		user.setName(mobile);
//		user.setNickName(mobile);
		user.setHasPlace(0);
		sqlManager.insert(user,true);
		
		UserBalance us = new UserBalance();
		us.setUserId(user.getId());
		us.setBalance(1000.00);
		us.setOwe(0.00);
		us.setUpdateTime(new Timestamp(new Date().getTime()));
		sqlManager.insert(us);
		
		
		return user;
	}
	@Override
	public void updateUser(SysUser user) {
		sqlManager.updateTemplateById(user);
		return ;
		
	}
	@Override
	public UserBalance getBalance(Integer userId) {
		UserBalance ub = new UserBalance();
		ub.setUserId(userId);
		return sqlManager.template(ub).get(0);
	}
	
	
	

}
